layui.use(['table', 'admin', 'ax'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;

    /**
     * Transport Order Management
     */
    var OrderTransport = {
        tableId: "orderTransportTable"
    };

    /**
     * Transport Order Details Management
     */
    var OrderTransportDetailed = {
        tableId: "orderTransportDetailedTable"
    };

    /**
     * 初始化表格的列
     */
    OrderTransport.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: 'Primary Key'},
            {field: 'center',align: 'center',width: 80, toolbar: '#tableBar', title: 'Action'},
            {field: 'customerOrder', sort: true, title: 'Customer Order No.', style:'color: #2b85e4;font-weight: 600;',width:150},
            {field: 'tstate', sort: true, title: 'Status',templet: '#tstateTpl', event: 'tstateSign'},
            {field: 'setMentiontime', sort: true, title: 'Shipping Date', style:'font-weight: 600;'},
            {field: 'undertime', sort: true, title: 'Order Time'},
            {field: 'createName', title: 'Created By'},
            {field: 'getUnit', title: 'Receiving Unit', style:'font-weight: 600;',width:180},
            {field: 'getLocation', title: 'Receiving Address',width:250},
            {field: 'getPeople', title: 'Contact Person'},
            {field: 'getTel', title: 'Contact Phone'},
            {field: 'nodes', title: 'Remarks', event: 'checkbox', totalRowText: 'Total:'},
            {field: 'kilometer', title: 'Kilometers'},
            {field: 'goodsNum', title: 'Goods Count', totalRow: true},
            {field: 'totalNum', title: 'Quantity', totalRow: true},
            {field: 'totalVolume', title: 'Volume', totalRow: true},
            
            {field: 'operateName', sort: true, title: 'Project'},
            {field: 'customerName', sort: true, title: 'Customer'},
            {field: 'transportNumber', sort: true, title: 'Transport Order No.', style:'color: #2b85e4;font-weight: 600;'},

            {field: 'lineName', title: 'Route'},
            
            {field: 'setUnit', title: 'Shipping Unit'},
            {field: 'setLocation', title: 'Shipping Address'},
            {field: 'createTime', sort: true, title: 'Creation Time'},
        ]];
    };

    /**
     * Click search button
     */
    OrderTransport.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        queryData['operateId'] = $("#operateId").val();
        queryData['customerId'] = $("#customerId").val();
        table.reload(OrderTransport.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };

    /**
     * Open add dialog
     */
    OrderTransport.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/orderTransport/add';
    };

    // Import Excel
    $('#btnExpimport').click(function () {
        layer.open({
            type: 2,
            title: 'Transport Order Import',
            area: ['1000px', '550px'],
            anim: 5,
            content: Feng.ctxPath + '/orderTransport/toimportExcel',
            end: function () {
                table.reload(OrderTransport.tableId);
                transportDetailed(null);
            }
        });
    });

    // Import Excel
    $('#btnExpimportXlb').click(function () {
        layer.open({
            type: 2,
            title: 'New Retail Help Picking Data Summary Excel Import',
            area: ['1000px', '550px'],
            anim: 5,
            content: Feng.ctxPath + '/orderTransport/toimportExcelXlb',
            end: function () {
                table.reload(OrderTransport.tableId);
                transportDetailed(null);
            }
        });
    });
		 
	// Pull New Retail Help Picking Tasks
    $('#pullxlbStoragetask').click(function () {
		submit = 2
        layer.open({
            type: 2,
            title: 'Pull New Retail Help Picking Tasks',
            area: ['850px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/orderTransport/topullxlbStoragetask',
            end: function () {
				if(submit == 1){
        			table.reload(OrderTransport.tableId);
				}
            }
        });
    });

    /**
     * Export Excel button
     */
    OrderTransport.exportExcel = function () {
        var checkRows = table.checkStatus(OrderTransport.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("Please select data to export");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };



    /**
     * Export Excel button
     */
    OrderTransport.exportExcel2 = function () {
        var checkRows = table.checkStatus(OrderTransport.tableId);
        var originalColumns = OrderTransport.initColumn()[0];
        var dataToExport = checkRows.data;
        if (checkRows.data.length === 0) {
            Feng.error("Please select data to export");
        } else {
            // table.exportFile(tableResult.config.id, checkRows.data, 'xls');
            dataToExport = dataToExport.map(function (row) {
                delete row.id; // 移除不需要的字段
                delete row.center;
                return row;
            });
            // 创建新的 columns 数组，只包含需要导出的列
            var exportColumns = originalColumns.filter(column => {
                // 排除表头
                return column.field !== 'id' && column.field !== 'center';
            });

            // 导出数据
            exportToXlsx(dataToExport, exportColumns);
        }
    };

    /**
     * Click edit
     *
     * @param data Row data when clicking the button
     */
    OrderTransport.openEditDlg = function (data) {
        window.location.href = Feng.ctxPath + '/orderTransport/edit?id=' + data.id;
    };

    // Render table
    var tableResult = table.render({
        elem: '#' + OrderTransport.tableId,
        url: Feng.ctxPath + '/orderTransport/list',
        page: true,
        limit: 40,
		limits:[40,60,120,240,360,480,1200],
        height: 400,
        cellMinWidth: 100,
        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        totalRow: true ,//开启合计行
        defaultToolbar: ['filter', 'exports', 'print'],
        cols: OrderTransport.initColumn()
    });
    
    // Batch submit
    $('#btnSubmission').click(function () {
    	var checkStatus = table.checkStatus('orderTransportTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
            	ids.push(data[i].id);
		}
		
            layer.confirm('Confirm submission of selected orders?', function(index){
            	layer.close(index);
            	var msg;
		        $.ajax({
		        	url:Feng.ctxPath + "/orderTransport/submission?ids="+ids,
		        	cache: false,
		        	dataType:"json",
		        	beforeSend:function(){
		            	// Show loading
		        msg = layer.load(1, {
		                    shade: [0.3,'#000'] //0.1透明度的白色背景
		                });
		        	},
		        	success:function(data){
		            	layer.close(msg); 
	                    if(data.success){
                    	Feng.success("Submission successful!");
	                        table.reload(OrderTransport.tableId);
	                        transportDetailed(null);
	                    } else {
	                        Feng.error("Submission failed!" + data.message + "!");
	                    }
		        	},
		        	error:function(data){
		            	layer.close(msg); 
                    	Feng.error("Submission failed!" + data.responseJSON.message + "!");
		        	}
		        })
            }); 
		} else {
			layer.alert('Please select at least one record');
		}
    });
    
    // Batch cancellation
    $('#btnTovoid').click(function () {
    	var checkStatus = table.checkStatus('orderTransportTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
            	ids.push(data[i].id);
			}
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/orderTransport/tovoid?ids="+ids, function (data) {
                    Feng.success("Submission successful!");
                    table.reload(OrderTransport.tableId);
                    transportDetailed(null);
                }, function (data) {
                    Feng.error("Submission failed!" + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("Confirm cancellation of selected orders?", operation);
		} else {
			layer.alert('Please select at least one record');
		}
    });

    // Search button click event
    $('#btnSearch').click(function () {
        OrderTransport.search();
    });

    // Add button click event
    $('#btnAdd').click(function () {
        OrderTransport.openAddDlg();
    });

    // Export Excel
    $('#btnExp').click(function () {
        OrderTransport.exportExcel();
    });

    // Export Excel
    $('#btnExp2').click(function () {
        OrderTransport.exportExcel2();
    });

    // Toolbar click event
    table.on('tool(' + OrderTransport.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') {
            OrderTransport.openEditDlg(data);
        }else if(obj.event === 'tstateSign'&&data.tstate=='REJECTED'){
			var index = layer.open({
				title: 'Review Details:',
			    type: 1,
			    title: false, //Don't show title bar
			    closeBtn: false,
			    shade: 0.3,
		        area: '300px;',
	        	content: "<div style='padding: 50px; word-wrap: break-word;word-break: break-all;overflow: hidden; background-color: #393D49; color: #fff;line-height: 22px;  font-weight: 300;'>Reviewer: "+data.auditName+"<br><br>Review Time: "+data.auditTime+"<br><br>Comments:<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+data.auditnode+"</div>",
	            btn: ['Confirm'] ,
	            yes: function(){
	                layer.close(index);
	            }
	    	});
	    }
    });
    
    /**
     * Initialize table columns - Details
     */
    OrderTransportDetailed.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: 'Primary Key'},
            {width: 120,align: 'center', toolbar: '#tableBarDetailed', title: 'Action'},
            {field: 'goodsName', sort: true, title: 'Product Name', style:'background-color: #dbf1e1;font-weight: 600;',width: 200},
            {field: 'goodsNumber', sort: true, title: 'Product Code', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'goodsNo', sort: true, title: 'Item No.', style:'background-color: #dbf1e1;font-weight: 600;', totalRowText: 'Total:'},
            {field: 'num', sort: true, title: 'Quantity', totalRow: true, style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'batchnumber', sort: true, title: 'Batch No.'},
            {field: 'unitprice', sort: true, title: 'Unit Price'},
            {field: 'transportMoney', sort: true, title: 'Amount', totalRow: true},
            {field: 'transportPutvolume', sort: true, title: 'Volume', totalRow: true},
            {field: 'transportWeight', sort: true, title: 'Weight', totalRow: true},
            {field: 'largeclass', title: 'Category'},
            {field: 'goodsUnit', title: 'Unit'},
            {field: 'dpacking', title: 'Packaging'},
            {field: 'goodsSpecs', title: 'Specifications'},
        ]];
    };

    // Row click event
    table.on('row(' + OrderTransport.tableId + ')', function (obj) {
        var data = obj.data;
		$('div[lay-id="' + OrderTransport.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + OrderTransport.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
        transportDetailed(data);
    });
    
    function transportDetailed(data){
    	var transportNumber;
    	if (data!=null) {
    		$("#transportNumber").val(data.transportNumber);
    		transportNumber = data.transportNumber;
		} else {
			transportNumber = 'nodata';
		}
        // Render product details table
        var tableResult = table.render({
            elem: '#' + OrderTransportDetailed.tableId,
            url: Feng.ctxPath + '/orderTransportDetailed/list?transportNumber=' + transportNumber,
            page: true,
            limit: 40,
            height: 390,
            toolbar: '#toolbarfromDetailed',
            cellMinWidth: 100,
            totalRow: true ,//开启合计行
            cols: OrderTransportDetailed.initColumn()
        });
        /**
         * Click search button
         */
    	OrderTransportDetailed.search = function () {
            var queryData = {};
            queryData['condition'] = $("#condition2").val();
            table.reload(OrderTransportDetailed.tableId, {
                where: queryData, page: {curr: 1},
                 done:function () {
                     // Search button click event
                     $('#btnSearchDetailed').click(function () {
                    	 OrderTransportDetailed.search();
                     });
			        $('#btnAddDetailed').click(function () {
			        	OrderTransportDetailed.addDetailed();
			        });
                }
            });
        };

    	OrderTransportDetailed.addDetailed = function () {
            layer.open({
                type: 2,
                title: 'Add Details',
                area: ['1000px', '500px'],
                anim: 5,
                content: Feng.ctxPath + '/orderTransportDetailed/add?transportNumber=' + data.transportNumber+"&customerId="+data.customerId,
                end: function () {
                	transportDetailed(data);
                }
            });
        };

        // Toolbar click event
        table.on('tool(' + OrderTransportDetailed.tableId + ')', function (obj) {
            var data2 = obj.data;
            var layEvent = obj.event;
            if (layEvent === 'editDetailed') {
            	OrderTransportDetailed.openEditDlg(data2);
            } else if (layEvent === 'deleteDetailed') {
            	OrderTransportDetailed.onDeleteItem(data2);
            }
        });

        // Edit button click event
        OrderTransportDetailed.openEditDlg = function (data2) {
            layer.open({
                type: 2,
                title: 'Edit Details',
                area: ['1000px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/orderTransportDetailed/edit?id='+data2.id+"&transportNumber="+data.transportNumber+"&customerId="+data.customerId,
                end: function () {
                	transportDetailed(data);
                }
            });
        };

        // Delete button click event
        OrderTransportDetailed.onDeleteItem = function (data2) {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/orderTransportDetailed/delete", function (data2) {
                    Feng.success("Deletion successful!");
                    transportDetailed(data);
                }, function (data) {
                    Feng.error("Deletion failed!" + data2.responseJSON.message + "!");
                });
                ajax.set("id", data2.id);
                ajax.start();
            };
            Feng.confirm("Confirm deletion?", operation);
        };

        // Search button click event
        $('#btnSearchDetailed').click(function () {
        	OrderTransportDetailed.search();
        });

        $('#btnAddDetailed').click(function () {
        	OrderTransportDetailed.addDetailed();
        });
    };
    
});
